package com.dharma.mydiet.view;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.dharma.mydiet.MainApplication;
import com.dharma.mydiet.R;
import com.dharma.mydiet.storage.DAOUser;
import com.dharma.mydiet.storage.TransactionalUser;
import com.dharma.mydiet.utility.Utils;
import com.dharma.mydiet.utility.Utils.TextFieldType;
import com.google.analytics.tracking.android.EasyTracker;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends Activity {
    // Values for email and password at the time of the login attempt.
    private String userName;
    private String mPassword;

    // UI references.
    private EditText mEmailView;
    private EditText mPasswordView;
    private View mLoginFormView;
    private View mLoginStatusView;
    private TextView mLoginStatusMessageView;
    private Button login;
    private Button signin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_login);

	login = (Button) findViewById(R.id.log_in_button);
	login.setOnClickListener(new OnClickListener() {
	    @Override
	    public void onClick(View v) {
		mEmailView = (EditText) findViewById(R.id.userName);
		mPasswordView = (EditText) findViewById(R.id.password);
		TransactionalUser user = DAOUser.getInstance().getUser(mEmailView.getText().toString());

		if (Utils.isValidTextField(TextFieldType.NONE, mEmailView.getText().toString())
			&& Utils.isValidTextField(TextFieldType.NONE, mPasswordView.getText().toString())
			&& user != null && user.getPassword().equals(mPasswordView.getText().toString())) {
		    Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
		    startActivity(intent);
		    ((MainApplication) getApplication()).setCurrentUser(user);
		} else {
		    mEmailView.setError("Combinacion invalida de cuenta y password.");
		}
	    }
	});
	signin = (Button) findViewById(R.id.sign_in_button);
	signin.setOnClickListener(new OnClickListener() {
	    @Override
	    public void onClick(View v) {
		Intent intent = new Intent(getApplicationContext(), SigninActivity.class);
		startActivity(intent);
	    }
	});

    }

    @Override
    public void onStart() {
	super.onStart();
	EasyTracker.getInstance(this).activityStart(this); // Add this method.
    }

    @Override
    public void onStop() {
	super.onStop();
	EasyTracker.getInstance(this).activityStop(this); // Add this method.
    }
}
